package cn.lg.soar.system.biz.modules.auth.service;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.system.biz.modules.auth.entity.PostTagRel;
import cn.lg.soar.system.biz.modules.auth.mapper.PostTagRelMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2022/4/10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class PostTagRelService extends ServiceImpl<PostTagRelMapper, PostTagRel> {

    /**
     * 获取职位标签
     * @param postId
     * @return
     */
    public List<Long> getTagIds(Long postId) {
        return listObjs(
                Wrappers.<PostTagRel>lambdaQuery()
                        .select(PostTagRel::getTagId)
                        .eq(PostTagRel::getPostId, postId),
                x -> Long.parseLong(x.toString())
        );
    }

    /**
     * 设置职位标签
     * @param postId
     * @param tagIds
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public void setPostTag(Long postId, Collection<Long> tagIds) {
        // 清空旧值
        clearByOrg(postId);

        if (CollectionUtils.isEmpty(tagIds)) {
            return;
        }
        // 批量保存新值
        List<PostTagRel> collect = tagIds.stream()
                .distinct()
                .map(x -> {
                    PostTagRel data = new PostTagRel();
                    data.setPostId(postId);
                    data.setTagId(x);
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存机构角色失败");
    }

    public void clearByOrg(Long postId) {
        this.remove(Wrappers.<PostTagRel>lambdaQuery().eq(PostTagRel::getPostId, postId));
    }

}
